package com.alex.mvppractice.news.model;

import android.os.Handler;

import com.alex.mvppractice.beans.NewsBean;
import com.alex.mvppractice.constant.UrlString;
import com.alex.mvppractice.utils.NewsJsonUtils;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * ***********************************************************
 * author: alex
 * time: 16/7/19 下午2:21
 * name:
 * overview:
 * usage:
 * *************************************************************
 */
public class NewsModelImpl implements NewsModel {
    @Override
    public void loadData(final String type, final OnResultListener listener) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(getUrl(type))
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onFailure();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                final List<NewsBean> datas = NewsJsonUtils.readJsonNewsBeans(result, type);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onSuccess(datas);
                    }
                });
            }
        });
    }

    Handler mHandler = new Handler();

    /**
     * 根据type值得到相应的url
     *
     * @param type
     * @return
     */
    public String getUrl(String type) {
        String url = "";
        switch (type) {
            case UrlString.TOP_ID:
                url = UrlString.URL_TOP;
                break;
            case UrlString.NBA_ID:
                url = UrlString.URL_NBA;
                break;
            case UrlString.CAR_ID:
                url = UrlString.URL_CAR;
                break;
            case UrlString.JOKE_ID:
                url = UrlString.URL_JOY;
                break;
        }
        return url;
    }
}
